import Taro, { Current } from '@tarojs/taro'
import React, { PureComponent } from 'react'
// 界面组件
import { View, Text, Button } from '@tarojs/components'
import { AtCheckbox, AtAvatar, AtTextarea, AtRate } from 'taro-ui'
import CTopbar from '@/components/CTopBar/index'
import CImage from '@/components/CImage/index'
import CCollegeMoreCard from '@/components/CCollegeMoreCard/index'
import CHomeMoreCard from '@/components/CHomeMoreCard/index'
import CComment from '@/components/CComment/index'
import { get_test_result_api, get_comment_list_api, submit_comment, get_order_result_api } from './service'
import './index.scss'
import GetTopBarInfo from '@/utils/GetTopBarInfo' //动态高度
/**
 * 首页测评 结果页
 */
type I = {
  showType: number //是否展示 咨询师，课程，测试题 三个列表  从订单进来不需要展示
  comment_list: any
  user_info: any
  userQuestionId: number
  id: number
  questionId: number
  value: string //评论输入框
  ratevalue1: number //评分
  ratevalue2: number //评分
  checkedvalue: any
  test_result: any
  pageNum: number
  pageSize: number
  isMore: boolean
  checkboxOption: any
}
interface HomeEvaluationResults {
  state: I
}
class HomeEvaluationResults extends PureComponent<any> {
  constructor(props) {
    super(props)
    this.state = {
      showType: 0, //是否展示 咨询师，课程，测试题 三个列表  从订单进来不需要展示
      comment_list: [],
      user_info: {},
      userQuestionId: 0,
      id: 0,
      questionId: 0,
      value: '', //评论输入框
      ratevalue1: 0, //评分
      ratevalue2: 0, //评分
      checkedvalue: [],
      test_result: {},
      pageNum: 1,
      pageSize: 10,
      isMore: false,
      checkboxOption: [
        {
          value: 'anonymous',
          label: '匿名提交',
        },
      ],
    }
  }

  componentWillMount() {
    const { userQuestionId, questionId, id, showType } = Current.router?.params
    const user_info = Taro.getStorageSync('user_info') || {}
    this.setState(
      {
        id: Number(id),
        user_info,
        questionId,
        userQuestionId: Number(userQuestionId),
        showType: Number(showType),
      },
      () => {
        // 获取结果信息
        if (showType) {
          this.get_order_result(userQuestionId)
        } else {
          this.get_test_result()
        }

        // 获取评论
        this.get_comment_list()
      },
    )
  }
  get_order_result(userQuestionId) {
    get_order_result_api(userQuestionId).then(({ result, data }) => {
      this.setState({
        test_result: data,
      })
    })
  }
  get_comment_list() {
    const { pageNum, pageSize, comment_list, questionId } = this.state
    get_comment_list_api(questionId, pageNum, pageSize).then(({ result, data }) => {
      // if (pageSize === data.length) {
      //   this.setState({
      //     isMore: true,
      //   })
      // }
      const arr = Array.from(data)
      this.setState({
        comment_list: comment_list.concat(...arr),
      })
      // this.setState({
      //   comment_list: data,
      // })
    })
  }
  // 下拉触底
  onReachBottom() {
    const { pageNum, isMore } = this.state
    // if (isMore) {
    this.setState(
      {
        pageNum: pageNum + 1,
      },
      () => {
        this.get_comment_list()
      },
    )
    // } else {
    //   Taro.showToast({
    //     icon: 'none',
    //     title: '没有数据啦',
    //     mask: true,
    //   })
    // }
  }
  get_test_result() {
    const { userQuestionId } = this.state
    const params = Taro.getStorageSync('TestResults')
    const questionInfo = JSON.stringify(params.questionInfo)
    params.questionInfo = questionInfo
    console.log(params)

    get_test_result_api(params).then(({ result, data }) => {
      this.setState({
        test_result: data,
      })
    })
  }
  goDetails(id) {
    Taro.navigateTo({
      url: '/pages/Consulting/ConsultingDetails/index?id=' + id,
    })
  }
  handleChange(value) {
    this.setState({
      value,
    })
  }
  RateHandleChange1(ratevalue1) {
    this.setState({
      ratevalue1,
    })
  }
  RateHandleChange2(ratevalue2) {
    this.setState({
      ratevalue2,
    })
  }
  handleChange3(checkedvalue) {
    this.setState({
      checkedvalue,
    })
  }
  toCourseDetail(id) {
    Taro.navigateTo({
      url: '/pages/Home/HomeCardDetails/index?id=' + id,
    })
  }
  gotoDetail(id) {
    Taro.navigateTo({
      url: '/pages/College/CourseDetails/index?id=' + id,
    })
  }

  submit() {
    const { id, value, ratevalue1, ratevalue2, checkedvalue, test_result } = this.state
    const isAnonymous = checkedvalue.indexOf('anonymous') === 0 ? 1 : 0
    if (value === '') {
      Taro.showToast({
        title: '请填写内容',
        icon: 'none',
        duration: 2000,
      })
      return
    }

    const params = {
      commentId: test_result.userQuestionId,
      comment: value,
      isAnonymous,
      accuracy: ratevalue1,
      satisfaction: ratevalue2,
      type: 1, //1代表测评
      pageNum: 1, //重新从第一页开始
    }
    submit_comment(params).then(({ result, data }) => {
      if (result > 0) {
        Taro.showToast({
          title: '评价成功',
          icon: 'none',
          duration: 2000,
        })
        this.setState(
          {
            value: '',
            ratevalue1: 0,
            ratevalue2: 0,
            checkedvalue: [],
          },
          () => {
            this.get_comment_list()
          },
        )
      }
    })
  }
  render() {
    const consultTeacherTypeArr = ['', '高级', '资深', '主任', '专家']
    const { user_info, test_result, comment_list = [], showType, checkboxOption, checkedvalue, ratevalue1, ratevalue2, value } = this.state
    return (
      <View className='pagewrap' style={{ paddingTop: `${GetTopBarInfo().TopBarHeight}px` }}>
        <View className='header'>
          <CTopbar title='动态标题' showBack></CTopbar>
        </View>
        <View className='colleg'>
          {/* 展示图 */}
          <View className='imageContainer'>{test_result ? <CImage src={test_result.questionImg}></CImage> : ''}</View>
          {/*测评信息 */}
          <View className='padding25'>
            {test_result ? <Text className='evaluation_title'>{test_result.questionName}</Text> : ''}
            {test_result ? <Text className='evaluation_time'>测试时间：{test_result.testTime}</Text> : ''}
          </View>

          {/* 测评结果 */}

          <View className='resultContent'>
            <View className='resultContent_avatar'>
              <CImage src={user_info.avatarUrl} circle={true}></CImage>
            </View>
            <View className='resultContent_name'>
              <Text>{user_info.nickName}</Text>
            </View>
            <View className='resultContent_box'>
              <Text>你的测试结果为</Text>
            </View>
            {/* 你的类型是XXX,详细介绍XXXX */}
            <View className='resultContent_text'>
              {test_result ? (
                <Text>
                  {test_result.analysisFraction &&
                    test_result.analysisFraction.map((item) => {
                      return `${item.dimensionName ? item.dimensionName : ''}
                      
                            ${item.analysisKey ? item.analysisKey + ' :' : ''}${item.analysisFraction ? item.analysisFraction : ''}
                            
                            `
                    })}
                </Text>
              ) : (
                ''
              )}
            </View>
          </View>
          {showType ? (
            ''
          ) : (
            <View>
              {test_result.therapist
                ? test_result.therapist.map((c, i) => {
                    return (
                      <View className='wrapper' key={c.id}>
                        <View className='at-row content'>
                          <View className='at-col at-col-1 at-col--auto '>
                            <AtAvatar image={c.therapistImg} circle={true} size='large'></AtAvatar>
                          </View>
                          <View className='at-col at-col--auto right '>
                            <View className='title'>{c.therapistName}</View>
                            <View className='rank'>国家{consultTeacherTypeArr[c.consultTeacherType]}心理咨询师</View>
                            {/* <View className='noto'>{c.briefIntroduction}</View> */}
                            <View className='footer'>
                              <View>
                                {c.price}/{c.time}分钟
                              </View>
                              <View>视频/当面</View>
                              <View>已关注</View>
                            </View>
                          </View>
                        </View>
                        <Button className='btn' onClick={this.goDetails.bind(this, c.id)}>
                          预约
                        </Button>
                      </View>
                    )
                  })
                : ''}
            </View>
          )}

          {/* 测试栏目 */}
          {showType ? (
            ''
          ) : (
            <View className='recommend_column'>
              <Text className='recommend_column_title'>大家都在测</Text>
              {test_result.question ? (
                test_result.question.map((c, i) => {
                  return (
                    <View onClick={this.toCourseDetail.bind(this, c.id)} className='test_wrapper'>
                      <CHomeMoreCard
                        img={c.questionImg}
                        title={c.questionName}
                        price={c.price}
                        subTitle={c.questionSubtitle}
                        personNum={c.questionNumber}
                        type={1}
                      />
                    </View>
                  )
                })
              ) : (
                <View className='not_found_data'>暂无数据~~</View>
              )}
            </View>
          )}

          {/* 课程栏目 */}
          {showType ? (
            ''
          ) : (
            <View className='recommend_column'>
              <Text className='recommend_column_title'>相关课程</Text>
              {test_result.course ? (
                test_result.course.map((c, i) => {
                  return (
                    <View key={c.id} onClick={this.gotoDetail.bind(this, c.id)} className='course_wrapper'>
                      <CCollegeMoreCard data={c} />
                    </View>
                  )
                })
              ) : (
                <View className='not_found_data'>暂无数据~~</View>
              )}
            </View>
          )}

          {/* 留言 */}
          <View className='LeavingMessage'>
            <Text className='LeavingMessage_title'>留言区</Text>
            <View className='LeavingMessage_input_warpper'>
              <View className='LeavingMessage_input'>
                <AtTextarea
                  value={value}
                  onChange={this.handleChange.bind(this)}
                  maxLength={200}
                  placeholderClass='placeholderClass'
                  placeholder='做完测评，感觉如何？给悦悦小姐姐留个言，说说你的感受吧～'
                />
              </View>
            </View>
            {/* 评分 */}
            <View className='score'>
              <View className='score_item'>
                <Text>准确度</Text>
                <AtRate value={ratevalue1} onChange={this.RateHandleChange1.bind(this)} />
              </View>
              <View className='score_item'>
                <Text>满意度</Text>
                <AtRate value={ratevalue2} onChange={this.RateHandleChange2.bind(this)} />
              </View>
            </View>
            {/* 复选框 */}
            <View className='check_wrapper'>
              <View className='check_center'>
                <AtCheckbox options={checkboxOption} selectedList={checkedvalue} onChange={this.handleChange3.bind(this)} />
              </View>
            </View>

            {/* 提交按钮 */}
            <View className='submit_wrapper'>
              <Text className='submit_btn' onClick={this.submit.bind(this)}>
                提交
              </Text>
            </View>
          </View>
          {/* 评论列表 */}
          <View className='comment_list'>
            {comment_list
              ? comment_list.map((c, i) => {
                  return (
                    <View key={i}>
                      <CComment data={c} />
                    </View>
                  )
                })
              : ''}
          </View>
        </View>
      </View>
    )
  }
}

export default HomeEvaluationResults
